package com.blb.servlet;

import com.blb.pojo.Pet;
import com.blb.pojo.Result;

import com.blb.pojo.Page;
import com.blb.pojo.Pet;
import com.blb.pojo.Result;
import com.blb.service.IPetService;
import com.blb.service.impl.PetServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/pet/*" , loadOnStartup = 1)
public class PetServlet extends BaseServlet{
    private IPetService petService=new PetServiceImpl();

    //qmj页面
    public void page(HttpServletRequest req, HttpServletResponse resp){
        String name = req.getParameter("name");
        int page = getPage();
        int size = getSize();
        try {
            Page<Pet> petPage = petService.selectPageByName(name, size, page);

            req.setAttribute("name", name);
            req.setAttribute("page", petPage);
            forward("/pet.jsp");
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    //删除
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        try {
            petService.delete(Integer.parseInt(id));
            writeJson(Result.ok("删除成功"));
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
            writeJson(Result.err("删除失败："+e.getMessage()));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加
     *
     * @param req
     * @param resp
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            Pet pet = getEntity(Pet.class);
            petService.add(pet);
            resp.sendRedirect("/pet/page");
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect("/add.jsp");
        }
    }

    //寵物更新方法
    public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            //獲取表單
            Pet pet = getEntity(Pet.class);
            //Service
            petService.update(pet);
            resp.sendRedirect("/pet/page");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //宠物更新页面
    public void updatePage(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        try {
            Pet pet = petService.updatePage(Integer.parseInt(id));
            req.setAttribute("pet",pet);
            forward("/update.jsp");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
